<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="roleRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="424"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="box-drawer">
      <BasicForm @register="roleForm" />
      <div class="drawer-tree">
        <div class="tree-title global-asterisk-require">角色权限</div>
        <div
          :class="drawerInfo.type === operateActionTypeMap.VIEW ? 'tree-list tree-view' : 'tree-list'"
          v-loading="treeLoading"
        >
          <a-tree
            defaultExpandAll
            blockNode
            v-model:checkedKeys="authTree.checkedKeys"
            @check="treeCheck"
            :checkable="checkable"
            :selectable="false"
            :tree-data="authTree.authTreeData"
            :fieldNames="{
              title: 'authorityName',
              key: 'authorityId'
            }"
            v-if="authTree.authTreeData.length"
          >
          </a-tree>
          <Empty v-if="!authTree.authTreeData.length && emptyInit"></Empty>
        </div>
      </div>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup name="roleAdd">
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { getRoleFormConfig } from '../dataSource'
import Empty from '@/components/Empty/index.vue'
import { userStore } from '@/store/modules/user'
import { toEleTreeData } from '@/utils'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import { operateActionType } from '@/types/enum'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import api from '@/api'

const { roleAdd, roleUpdate, roleDetail } = api

const emit = defineEmits(['operateSuccess', 'register'])

const userModule = userStore()
const operateActionTypeMap = operateActionType

const treeLoading = ref(false)
const checkable = ref(false)
const emptyInit = ref(false)
const drawerInfo = reactive({
  type: '',
  roleId: ''
})

const authTree = reactive<any>({
  checkedKeys: [],
  halfCheckedKeys: [],
  allLastKeys: [],
  authTreeData: []
})
const roleFormConfig = getRoleFormConfig()

const [roleForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema }] = useForm(roleFormConfig)

const [roleRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  emptyInit.value = false
  drawerInfo.type = data.type

  // 查看时表单展示
  updateSchema(getUpdateSchemaArr(roleFormConfig.schemas, data.type))

  if (data.type === operateActionTypeMap.VIEW) {
    checkable.value = false
  } else {
    checkable.value = true
    authTree.authTreeData = userModule.authList
  }
  if (data.type !== operateActionTypeMap.ADD) {
    let record = cloneDeep(data.record)
    setFieldsValue({
      ...record
    })
    drawerInfo.roleId = record.roleId

    try {
      treeLoading.value = true
      let res = await roleDetail({ roleId: record.roleId })
      treeLoading.value = false
      let authorityList = res.result?.authorityList
      if (data.type === operateActionTypeMap.EDIT) {
        deepLastNode(userModule.authList)
        let checkedKeys: any[] = []
        let halfCheckedKeys: any[] = []
        if (authorityList && authorityList.length) {
          authorityList.forEach((item: any) => {
            if (authTree.allLastKeys.includes(item.authorityId)) {
              checkedKeys.push(item.authorityId)
            } else {
              halfCheckedKeys.push(item.authorityId)
            }
          })
        }
        authTree.checkedKeys = checkedKeys
        authTree.halfCheckedKeys = halfCheckedKeys
      } else {
        let authTreeData = toEleTreeData(authorityList)
        authTree.authTreeData = authTreeData
      }
    } catch (error) {
      treeLoading.value = false
    }
  }
  emptyInit.value = true
})

const deepLastNode = (data: any) => {
  data.map((item: any) => {
    if (item.children && item.children.length > 0) {
      deepLastNode(item.children)
    } else {
      authTree.allLastKeys.push(item.authorityId)
    }
  })
}

const drawerReset = () => {
  resetFields()
  changeOkLoading(false)
  emptyInit.value = false
  authTree.checkedKeys = []
  authTree.halfCheckedKeys = []
  authTree.authTreeData = []
}

// 权限勾选赋值半节点
const treeCheck = (checkedKeys: any[], e: any) => {
  authTree.halfCheckedKeys = e.halfCheckedKeys
}
// 提交数据
const confirmSubmit = async () => {
  let authorityIds = [...authTree.checkedKeys, ...authTree.halfCheckedKeys]
  try {
    await validate()
    if (!authorityIds.length) {
      return message.warn('请选择角色权限')
    }
    let formValue = getFieldsValue()
    changeOkLoading(true)
    if (drawerInfo.type === operateActionTypeMap.ADD) {
      await roleAdd({
        authorityIds,
        ...formValue
      })
    } else if (drawerInfo.type === operateActionTypeMap.EDIT) {
      await roleUpdate({
        authorityIds,
        ...formValue,
        roleId: drawerInfo.roleId
      })
    }
    message.success(drawerInfo.type === operateActionTypeMap.ADD ? '角色新增成功' : '角色编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.box-drawer {
  padding: 8px 44px;
  .drawer-tree {
    border: 1px solid #e0e1e6;
    border-radius: 4px;
    .tree-title {
      height: 44px;
      line-height: 44px;
      padding-left: 4px;
      color: @text-color;
      font-size: 12px;
      font-weight: 600;
      background: #fafafa;
      border-bottom: 1px solid #e0e1e6;
    }
    .tree-list {
      padding: 8px 0;
      height: 400px;
      overflow: auto;
      position: relative;
    }
    :deep(.tree-view) {
      .ant-tree-node-content-wrapper-open,
      .ant-tree-node-content-wrapper-close {
        .ant-tree-title {
          color: #cdcdcd;
        }
      }
      .ant-tree-node-content-wrapper-normal {
        position: relative;
        &::before {
          content: '';
          width: 7px;
          height: 11px;
          position: absolute;
          left: -12px;
          top: 5px;
          border: 2px solid @primary-color;
          border-top: 0;
          border-left: 0;
          transform: rotate(45deg);
          transform-origin: center;
        }
      }
    }
  }
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
}
</style>
